import urllib.request


def load_baidu():
    url = 'http://www.baidu.com'

    # headers = {
    #
    #     # 浏览器 请求
    #     "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"
    # }

    # 创建请求对象
    # request = urllib.request.Request(url, headers=headers)

    request = urllib.request.Request(url)

    request.add_header("User-Agent","myuser######CCCDDFDFFD")

    response = urllib.request.urlopen(request)

    data = response.read().decode('utf-8')

    # 获取请求 头  request_headers
    # request_headers = request.get_header('User-agent')
    # print(request_headers)

    # 获取响应头 response.headers
    print(response.headers)


    # 获取完整的 url
    final_url = request.get_full_url()
    print(final_url)
    # 保存
    with open('01header.html', 'w') as f:
        f.write(data)


load_baidu()
